angular.module('U9ImHd.services')

.factory('User', ['$rootScope', '$q', '$ionicHistory', 'AppManager', 'Connect', 'Auth', 'Http', 'Config', 'Help', 'APPCONSTANTS', 
    function($rootScope, $q, $ionicHistory, AppManager, Connect, Auth, Http, Config, Help, APPCONSTANTS) {
        var userDefer = $q.defer(),
            o = {
                loaded: userDefer.promise
            };

        var _user = null;

        o.signin = function (usercode, password, autologin) {
            var defer = $q.defer();

            Http.post({
                url: APPCONSTANTS.signinURL,
                data: {
                    usercode: usercode,
                    password: password
                }
            }).then(function (data) {
                Auth.setAuth(true, data.token);
                var token = autologin ? data.token : '';
                return Config.set('token', token);
            }).then(function () {
                return AppManager.installApps();
            }).then(function () {
                return queryMe();
            }).then(function (user) {
                _user = user;
                $rootScope.$broadcast('signin', user);
                return $ionicHistory.clearCache(['home']);
            }).then(function () {
                defer.resolve();
            }).catch(function (err) {
                defer.reject(err);
            });

            return defer.promise;
        };
        o.signinScan = function (barcode) {
            var defer = $q.defer();

            Http.post({
                url: APPCONSTANTS.signinScanURL,
                data: {
                    Barcode: barcode
                }
            }).then(function (data) {
                Auth.setAuth(true, data.token);
                return AppManager.installApps();
            }).then(function () {
                return queryMe();
            }).then(function (user) {
                _user = user;
                $rootScope.$broadcast('signin', user);
                return $ionicHistory.clearCache(['home']);
            }).then(function () {
                defer.resolve();
            }).catch(function (err) {
                defer.reject(err);
            });

            return defer.promise;
        };
        o.signout = function () {
            var defer = $q.defer();

            Config.set('token', '').then(function () {
                Auth.setAuth(false);
                _user = null;
                $rootScope.$broadcast('signout');
                defer.resolve();
            }, function () {
                defer.reject();
            });

            return defer.promise;
        };
        o.get = function (key) {
            if (!_user) {
                return null;
            }
            return key ? _user[key] : angular.copy(_user);
        };

        init();

        return o;

        function init () {
            Connect.loaded.finally(function () {
                var token = Config.get('token');
                if (!token) {
                    userDefer.resolve();
                } else {
                    Auth.setAuth(true, token);
                    queryMe().then(function (user) {
                        _user = user;
                        $rootScope.$broadcast('signin', user);
                    }, function () {
                        Auth.setAuth(false, '');
                    }).finally(function () {
                        AppManager.installApps().finally(function () {
                            userDefer.resolve();
                        });
                    });
                }
            });
        }
        function queryMe () {
            var defer = $q.defer();

            Http.get({
                url: APPCONSTANTS.getMeURL,
                ignoreErrorHandler: true
            }).then(function (user) {
                if (user.Image) {
                    user.Image = Help.getFullURL(user.Image);
                }
                defer.resolve(user);
            }, function (err) {
                defer.reject(err);
            });

            return defer.promise;
        }
    }
]);
